package com.mall.sun.service.impl;

import com.alibaba.fastjson.JSON;
import com.mall.sun.model.dto.ImageIdentifyDTO;
import com.mall.sun.service.ImageIdentifyService;
import com.mall.sun.utils.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.List;

/**
 * description:  <br>
 * date: 2021/12/9 20:56 <br>
 * author: ztz <br>
 * version: 1.0 <br>
 */
@Service
public class ImageIdentifyImpl implements ImageIdentifyService {
    @Autowired
    HttpUtil httpUtil;
    private static String accessToken = null;
    static {
        accessToken = AuthService.getAuth();
    }

    @Override
    public List<ImageIdentifyDTO> getImageResult(String base64) {
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient";
        try {
            // 本地文件路径
            //byte[] imgData = FileUtil.readFileByBytes(filePath);
            //String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(base64, "UTF-8");
            String param = "image=" + imgParam;
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String result = HttpUtil.post(url, accessToken, param);
            List<ImageIdentifyDTO> list = JsonUtil.getListByJSONArray(ImageIdentifyDTO.class, JSON.parseObject(result).getString("result"));
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
